import 'storage.dart';

class SearchService {
  // 添加搜索记录
  static addHistoryData(String keywords) async {
    // 避免添加重复的数据
    List? historyList = await Storage.getData("historyList");
    if (historyList != null) {
      if (!historyList.contains(keywords)) {
        // 当当前不存在这个key时才能添加
        historyList.add(keywords);
        await Storage.setData("historyList", historyList);
      }
    } else {
      // 如果没有数据，则直接添加
      List<String> tempList = [];
      tempList.add(keywords);
      await Storage.setData("historyList", tempList);
    }
  }

  // 获取历史搜索记录
  static Future<List> getHistoryData() async {
    List? historyList = await Storage.getData("historyList");
    if (historyList != null) {
      return historyList;
    } else {
      return [];
    }
  }

  // 删除某个搜索记录
  static removeHistoryData(String keywords) async {
    List? historyList = await Storage.getData("historyList");
    if (historyList != null) {
      historyList.remove(keywords);
      await Storage.setData("historyList", historyList);
    }
  }

  // 清空全部历史搜索记录
  static Future clearHistoryData() async {
    List? historyList = await Storage.getData("historyList");
    if (historyList != null) {
      historyList.clear();
      await Storage.setData("historyList", historyList);
    }
  }
}
